<template>
	<view>
		<topDropdown :isSxShow="true" :isPaiXu="true" :isDuoXuan="true"
            :dropdown1="dropdown1" :options1="options1" :optionsPx="optionsPx"  :optionsSx="sxList" 
            searchLabel1="供应商名称" 
            searchPh1="请输入供应商名称"
			@searchBoxEmitFun="searchBoxEmitFun" 
            @dropDownFun1="dropDownFun1" 
            @optionSxFun="optionSxFun"
			@optionPxFun="optionPxFun">
		</topDropdown>
		<scroll-view scroll-y="true" :style="{height: scrollHeight}" @scrolltolower="selectSupplierFun" refresher-enabled
			:refresher-threshold="200" :refresher-triggered="triggered" refresher-background="gray"
			@refresherrefresh="onRefresh" @refresherrestore="onRestore">
			<view v-if="list.length > 0">
				<view v-for="(item, index) in list" :key="index" @click="supplierCardClickFun(item)">
					<supplierCard :item="item" :isSelect="isSelect" :index="index" @afreshGetDataFun="afreshGetDataFun">
					</supplierCard>
				</view>
				<getMore :isMore="isMore" nullMsg="已加载全部~"></getMore>
				<view class="h200"></view>
			</view>
			<dataNull v-else src="/static/img/dataNull.png" title="暂无相关供应商哦~"></dataNull>
		</scroll-view>
		<addBtn url="./add"></addBtn>
		<u-action-sheet :list="sheetList" v-model="moreShow"></u-action-sheet>
	</view>
</template>

<script>
	import { apiSupSupplier } from '@/api/crm.js'
	import {tyDropDown, dropDownByUser, supSxDropDownData, datePxData} from '@/utils/dropdown.js'
	import {getDayFun,formatDate,getDayByNumFun} from '@/utils/date.js'

	import dataNull from '@/components/dataNull/dataNull.vue'
	import addBtn from '@/components/addBtn/addBtn.vue'
	import getMore from '@/components/getMore/getMore.vue'
	import topDropdown from '@/components/topDropdown/topDropdown.vue'
	import supplierCard from '@/components/card/supplierCard.vue'

	export default {
		components: {
			dataNull,
			addBtn,
			getMore,
			topDropdown,
			supplierCard
		},
		data() {
			return {
				triggered: false,
				dropdown1: '全部',// 第一个下拉框默认值
				options1: tyDropDown,// 第一个下拉框数据
				optionsPx: datePxData,// 第二个下拉框数据
	
				sxList: [],
				list: [],
				moreShow: false,
				sheetList: [{
						text: '添加合作记录'
					},
					{
						text: '添加标签'
					}
				],
				isMore: true,
				pageNum: 1,
				scrollHeight: '667px',
				pageType: '',
				sortObj: {
					updatetime: 'desc'
				},
				optionsReq: {listtype:'selfson'}, // 第一个下拉框请求参数
				sortReq: {}, // 第二个排序请求参数
				sxReq: {}, // 第三个多选择筛选想请求参数
				matchObj: {},
				searchValue: '',
				dateReq: [], // 日期相关请求参数
				isSelect: false,
				tabNoEqualArr: [] //标签页不等于数据
			}
		},
		onLoad(e) {
			this.initPage(e)
		},
		onBackPress() {
			// 清理事件监听器
			const events = ['deleteSupplierFun', 'updateListByIndex', 'addItemInListFun', 'afreshGetDataFun']
			events.forEach(event => uni.$off(event, this[event]))
		},
		methods: {
			/**
			 * 页面初始化
			 */
			initPage(e) {
				// 初始化筛选条件
				this.initFilterConditions()
				
				// 设置页面类型和模式
				this.pageType = e.type || ''
				this.isSelect = !!e.type

				// 设置滚动区域高度
				this.setScrollHeight()

				// 查询供应商数据
				this.selectSupplierFun()

				// 注册全局事件
				this.registerGlobalEvents()
			},

			/**
			 * 初始化筛选条件
			 */
			initFilterConditions() {
				const supDictSx = uni.getStorageSync('cstDictSx') || {}
				const dynamicFilters = [
					{ title: '经济类型', field: 'ecotype', current: '', arr: supDictSx.ecotype || [] },
					{ title: '等级', field: 'level', current: '', arr: supDictSx.level || [] },
					{ title: '行业', field: 'industry', current: '', arr: supDictSx.industry || [] },
				]
				this.sxList = supSxDropDownData.concat(dynamicFilters)
			},

			/**
			 * 设置滚动区域高度
			 */
			setScrollHeight() {
				uni.getSystemInfo({
					success: (res) => {
						this.scrollHeight = res.windowHeight - 40 + 'px'
					}
				})
			},

			/**
			 * 注册全局事件
			 */
			registerGlobalEvents() {
				const events = {
					'deleteSupplierFun': this.deleteSupplierFun,
					'updateListByIndex': this.updateListByIndex,
					'addItemInListFun': this.addItemInListFun,
					'afreshGetDataFun': this.afreshGetDataFun
				}
				Object.entries(events).forEach(([event, handler]) => {
					uni.$on(event, handler)
				})
			},
			/**
			 * 查询供应商数据
			 */
			async selectSupplierFun() {
				if (!this.isMore) return

				uni.showLoading({ title: '加载中...', mask: true })

				try {
					const reqObj = this.buildRequestParams()
					console.log('执行查询', reqObj)

					const reqData = {
						action: 'get_list',
						params: reqObj
					}

					const res = await apiSupSupplier(reqData)
					this.handleApiResponse(res)
				} catch (error) {
					this.handleApiError(error)
				}
			},

			/**
			 * 构建请求参数
			 */
			buildRequestParams() {
				const baseParams = {
					create_user_id: uni.$userInfo.id,
					keywords: this.searchValue,
				}

				return {
					matchObj: Object.assign(baseParams, this.optionsReq, this.sxReq),
					sortObj: this.sortReq,
					pageNum: this.pageNum,
				}
			},

			/**
			 * 处理API响应
			 */
			handleApiResponse(res) {
				const data = res.data.data
				console.log('API响应数据:', data)

				// 清空列表（第一页时）
				if (this.pageNum === 1) {
					this.list = []
				}

				// 更新页码和加载状态
				this.isMore = data.length === 10
				if (this.isMore) {
					this.pageNum += 1
				}

				// 合并数据
				this.list = [...this.list, ...data]
				this.triggered = false
				setTimeout(() => uni.hideLoading(), 500)
			},

			/**
			 * 处理API错误
			 */
			handleApiError(error) {
				console.error('查询供应商失败:', error)
				uni.hideLoading()
				uni.showToast({ title: '加载失败', icon: 'none' })
			},
		// 供应商点击方法
		supplierCardClickFun: function(item) {
			console.log(this.pageType);
			if (this.pageType == 'add_purchase_goback') {
				uni.$emit('supplierBindFun', {
					supplier_name: item.name,
					supplier_id: item.id
				})
				uni.navigateBack()
			} else if (this.pageType == 'add_receipt_goback') {
				uni.$emit('receiptSupplierBindFun', {
					supplier_name: item.name,
					supplier_id: item.id
				})
				uni.navigateBack()
			} else if (this.pageType == 'add_invoice_goback') {
				uni.$emit('invoiceSupplierBindFun', {
					supplier_name: item.name,
					supplier_id: item.id
				})
				uni.navigateBack()
			} else if (this.pageType == 'add_pos_contract_goback') {
				uni.$emit('posContractSupplierBindFun', {
					supplier_name: item.name,
					supplier_id: item.id
				})
				uni.navigateBack()
			} else if (this.pageType == 'fin_pay_record') {
				uni.$emit('supplierBindFun', {
					supplier_name: item.name,
					supplier_id: item.id
				})
				uni.navigateBack()
			} else if (this.pageType == 'fin_rece_record') {
				uni.$emit('supplierBindFun', {
					supplier_name: item.name,
					supplier_id: item.id
				})
				uni.navigateBack()
			} else if (this.pageType != '') {
				uni.$emit('supplierBindFun', item)
				uni.navigateBack()
			}
		},
			// 下拉框回调函数
			dropDownFun1: function(e) {

				let optionsReq = {};
				let userInfo = uni.$userInfo;
				this.listtype = undefined;
				if (e.label == '全部') {
					optionsReq.listtype = 'selfson';
				} else if (e.label == '我负责的') {
					optionsReq.listtype = 'self';
				} else if (e.label == '下属负责') {
					optionsReq.listtype = 'son';
				} else{
                    this.listtype='selfson'
                }
				this.optionsReq = optionsReq;
				console.log('下拉回调的参数')
				console.log(optionsReq)

				this.afreshGetDataFun();
			},
			// 筛选框回调函数
			optionSxFun: function(arr) {
				let matchReq = [];
				let dateReq = [];
				for (var i = 0; i < arr.length; i++) {
					if (arr[i].current !== '' && !arr[i].isDate) {
						matchReq.push({
							field: arr[i].field,
							value: arr[i].arr[arr[i].current]
						})
					} else if (arr[i].current !== '' && arr[i].isDate) {
						dateReq.push({
							field: arr[i].field,
							value: formatDate(arr[i].sTime) + '-' + formatDate(arr[i].eTime)
						})
					}
				}
				let reqObj = {};
				// 动态生成请求对象
				for (var i = 0; i < matchReq.length; i++) {
					reqObj[matchReq[i].field] = matchReq[i].value
				}
				//时间参数处理
				for (var i = 0; i < dateReq.length; i++) {
					reqObj[dateReq[i].field] = dateReq[i].value
				}
				this.sxReq = reqObj;

				console.log('筛选回调的参数')
				console.log(reqObj)

				this.afreshGetDataFun();
			},
			
			// 排序筛选框回调函数
			optionPxFun: function(arr) {
				let sortObj = {
					orderField: ''
				}
				let direaction = '';
				for (var i = 0; i < arr.length; i++) {
					if (arr[i].current !== '') {
						sortObj = {}
						if (arr[i].field == 'create_time') {
							sortObj.orderDirection = arr[i].current == 1 ? 'asc' : 'desc'
						}
						if (arr[i].field == 'update_time') {
							sortObj.orderDirection = arr[i].current == 1 ? 'asc' : 'desc'
						}
						sortObj.orderField = arr[i].field;
						break;
					}
				}
				this.sortReq = sortObj;
				console.log('排序回调的参数')
				console.log(sortObj)

				this.afreshGetDataFun();
			},
			// 搜索框回调方法
			searchBoxEmitFun: function(e) {
				this.searchValue = e.searchValue1;
				this.afreshGetDataFun()
			},
			// 下拉刷新
			onRefresh: function() {
				if (this.triggered) return
				this.triggered = true;
				this.afreshGetDataFun();
			},
			onRestore: function(e) {
				this.triggered = false; // 需要重置
			},
			// 重新获取数据
			afreshGetDataFun: function() {
				this.pageNum = 1;
				this.isMore = true;
				this.selectSupplierFun();
			},
			deleteSupplierFun: function(e) {
				this.list.splice(e.index, 1);
			},
			// 通过下标更新list数据
			updateListByIndex: function(e) {
				this.$set(this.list, parseInt(e.index), e.obj)
			},
			// add页面新增数据
			addItemInListFun: function(e) {
				this.list.unshift(e);
				uni.pageScrollTo({
					scrollTop: 0
				})
			}
		}
	}
</script>

<style>
	page {
		background-color: #F8F8F8;
	}

	.h200 {
		height: 200rpx;
	}
</style>